# install-office.ps1
# Installs Microsoft Office using the Office Deployment Tool and the configuration XML
# included in this FileWave Fileset.

$OfficeRoot = "C:\ProgramData\FileWave\Installers\Office"
$SetupExe = Join-Path $OfficeRoot "setup.exe"
$ConfigXml = Join-Path $OfficeRoot "configuration.xml"
$LogRoot = "C:\ProgramData\FileWave\Logs"
$LogFile = Join-Path $LogRoot "office-install.log"

# Ensure logging directory exists.
if (-not (Test-Path $LogRoot)) {
    New-Item -Path $LogRoot -ItemType Directory -Force | Out-Null
}

function Write-Log {
    param (
        [string]$Message
    )

    $Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    "$Timestamp $Message" | Tee-Object -FilePath $LogFile -Append
}

Write-Log "Starting Microsoft Office installation."

# Validate required files before attempting installation.
if (-not (Test-Path $SetupExe)) {
    Write-Log "ERROR: setup.exe not found at $SetupExe"
    exit 1
}

if (-not (Test-Path $ConfigXml)) {
    Write-Log "ERROR: configuration.xml not found at $ConfigXml"
    exit 1
}

try {
    $Process = Start-Process -FilePath $SetupExe `
        -ArgumentList "/configure `"$ConfigXml`"" `
        -Wait `
        -PassThru `
        -WindowStyle Hidden

    Write-Log "Office Deployment Tool exited with code $($Process.ExitCode)."

    if ($Process.ExitCode -ne 0) {
        Write-Log "ERROR: Office installation failed."
        exit $Process.ExitCode
    }

    Write-Log "Microsoft Office installation completed successfully."
    exit 0
}
catch {
    Write-Log "ERROR: $($_.Exception.Message)"
    exit 1
}